package com.ruoyi.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.Amount.service.impl.AmountReduceImpl;
import com.ruoyi.H5Send.demo.SmsVariableSend;
import com.ruoyi.SuveryInterface.Imp.mapper.*;
import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.domain.SysInterfacePrice;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.agent.mapper.SysInterfacePriceMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.messages.NotifyUtils;
import com.ruoyi.messages.service.impl.SysNotifyServiceImpl;
import com.ruoyi.order.Utils.OrderUtils;
import com.ruoyi.order.domain.*;
import com.ruoyi.order.mapper.SysOrderOneMapper;
import com.ruoyi.order.service.ISysOrderOneService;
import com.ruoyi.orderParent.domain.SysOrder;
import com.ruoyi.orderParent.domain.SysOrderParent;
import com.ruoyi.orderParent.mapper.SysOrderParentMapper;
import com.ruoyi.packages.Utils.SurveyUtils;
import com.ruoyi.packages.domain.SysPackage;
import com.ruoyi.packages.domain.SysSurvey;
import com.ruoyi.packages.domain.SysSurveyPackage;
import com.ruoyi.packages.mapper.SysPackageMapper;
import com.ruoyi.packages.mapper.SysSurveyMapper;
import com.ruoyi.packages.service.ISysSurveyService;
import com.ruoyi.packages.service.impl.SysSurveyServiceImpl;
import com.ruoyi.report.domain.SysReport;
import com.ruoyi.report.domain.SysReportDetails;
import com.ruoyi.report.mapper.SysReportDetailsMapper;
import com.ruoyi.report.mapper.SysReportMapper;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.storeAdd.domain.SysExpendDetails;
import com.ruoyi.storeAdd.mapper.SysExpendDetailsMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 背调订单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-24
 */
@Service
public class SysOrderOneServiceImpl implements ISysOrderOneService
{
    @Autowired
    private SysOrderOneMapper sysOrderOneMapper;
    @Autowired
    private SysStoreMapper sysStoreMapper;

    @Autowired
    private SysPackageMapper packageMapper;


    @Autowired
    private SysAgentMapper agentMapper;

    @Autowired
    private SysSurveyMapper surveyMapper;

    @Autowired
    private SysInterfacePriceMapper interfacePriceMapper;

    @Autowired
    private SysOrderParentMapper orderParentMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysExpendDetailsMapper expendDetailsMapper;

//    @Autowired
//    private SysNotifyServiceImpl notifyService;

    @Autowired
    private RedisTemplate redisTemplate;

//    @Autowired
//    private ISysSurveyService sysSurveyService;
//
//    @Autowired
//    private SysCreditMapper creditMapper;
//
//
//    @Autowired
//    private SysDegreesMapper degreesMapper;
//
//    @Autowired
//    private SysDegreeDetailsMapper degreeDetailsMapper;
//
//    @Autowired
//    private SysEducationDetailsMapper educationDetailsMapper;
//
//    @Autowired
//    private SysCommercialMapper commercialMapper;
//
//    @Autowired
//    private SysLegalInfosMapper legalInfosMapper;
//    @Autowired
//    private SysShareholderInfosMapper shareholderInfosMapper;
//
//    @Autowired
//    private SysManagerInfosMapper managerInfosMapper;
//
//    @Autowired
//    private SysPunishedsMapper punishedsMapper;
//
//    @Autowired
//    private SysPunishBreaksMapper punishBreaksMapper;
//
//    @Autowired
//    private SysAdminPenaltyMapper adminPenaltyMapper;
//
//    @Autowired
//    private SysIdentityMapper identityMapper;
//
//    @Autowired
//    private SysIdentityCasesMapper identityCasesMapper;
//
//    @Autowired
//    private SysIdentitySxbzxrMapper identitySxbzxrMapper;
//
//    @Autowired
//    private SysIdentityXgbzxrMapper xgbzxrMapper;
//
//    @Autowired
//    private SysIdentityDsrxxMapper dsrxxMapper;
//
//
//    @Autowired
//    private SysNegativeMapper negativeMapper;
//
//    @Autowired
//    private SysNegativeDetailsMapper negativeDetailsMapper;

    @Autowired
    private SysReportDetailsMapper reportDetailsMapper;


    @Autowired
    private SysReportMapper reportMapper;

//    @Autowired
//    private WordExportController wordExportController;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private NotifyUtils notifyUtils;

    @Autowired
    private SurveyUtils surveyUtils;



    /**
     * 查询背调订单
     *
     * @param id 背调订单主键
     * @return 背调订单
     */
    @Override
    public SysOrderOne selectSysOrderOneById(Long id)
    {
        return sysOrderOneMapper.selectSysOrderOneById(id);
    }

    /**
     * 查询背调订单列表
     *
     * @param sysOrderOne 背调订单
     * @return 背调订单
     */
    @Override
    public List<SysOrderOne> selectSysOrderOneList(SysOrderOne sysOrderOne)
    {
        return sysOrderOneMapper.selectSysOrderOneList(sysOrderOne);
    }

    /**
     * 新增背调订单
     *
     * @param sysOrderOne 背调订单
     * @return 结果
     */
    @Override
    public int insertSysOrderOne(SysOrderOne sysOrderOne)
    {
        sysOrderOne.setCreateTime(DateUtils.getNowDate());
        return sysOrderOneMapper.insertSysOrderOne(sysOrderOne);
    }

    /**
     * 修改背调订单
     *
     * @param sysOrderOne 背调订单
     * @return 结果
     */
    @Override
    public int updateSysOrderOne(SysOrderOne sysOrderOne)
    {
        sysOrderOne.setUpdateTime(DateUtils.getNowDate());
        return sysOrderOneMapper.updateSysOrderOne(sysOrderOne);
    }

    /**
     * 批量删除背调订单
     *
     * @param ids 需要删除的背调订单主键
     * @return 结果
     */
    @Override
    public int deleteSysOrderOneByIds(Long[] ids)
    {
        return sysOrderOneMapper.deleteSysOrderOneByIds(ids);
    }

    /**
     * 删除背调订单信息
     *
     * @param id 背调订单主键
     * @return 结果
     */
    @Override
    public int deleteSysOrderOneById(Long id)
    {
        return sysOrderOneMapper.deleteSysOrderOneById(id);
    }

    @Override
    @Transactional
    public OrderOneVO submitOneOrder(OrderDTO orderDTO) {
        //单人背调下单后，生产订单数据，但支付状态为未支付，返回给前端封装的数据
        SysOrderOne sysOrderOne = new SysOrderOne();
        //进行数据的封装
        //1.生产订单号 todo
         Long packageId = orderDTO.getPackageId();
                SysPackage sysPackage = packageMapper.selectSysPackageById(packageId);
        String orderNum = OrderUtils.MakeOrderByDate(sysPackage.getLineStatus(), new Date());
        sysOrderOne.setNumber(orderNum);

        //2.已有数据封装
        sysOrderOne.setCdName(orderDTO.getUserName());
        sysOrderOne.setIdNumber(orderDTO.getCard());
        if (!StringUtils.isEmpty(orderDTO.getCerNo())) {
            sysOrderOne.setCertificate(orderDTO.getCerNo());
        }
        if (!StringUtils.isEmpty(orderDTO.getDegreeCerNo())) {
            sysOrderOne.setDegreeCerNo(orderDTO.getDegreeCerNo());
        }
        sysOrderOne.setAmount(orderDTO.getAmount());
        sysOrderOne.setPhone(orderDTO.getPhone());
        sysOrderOne.setAuthorizationType(orderDTO.getAuthorizedType());
        sysOrderOne.setPayStatus(0l);
        sysOrderOne.setOrderStatus(0l);
        sysOrderOne.setOrderOutcome(1l);
        //根据当前登录用户获取商户对象
        Long deptId = SecurityUtils.getDeptId();
//        Long deptId = 100l;

        List<SysStore> sysStores = sysStoreMapper.selectSysStoreByDeptId(deptId);
        if (CollectionUtils.isEmpty(sysStores)) {
            throw new ServiceException("当前用户商户信息有误");
        }
        SysStore sysStore = sysStores.get(0);

        sysOrderOne.setStoreId(sysStore.getId());
        sysOrderOne.setStoreName(sysStore.getName());
        sysOrderOne.setAgentId(sysStore.getAgentId());
        sysOrderOne.setSetmealId(orderDTO.getPackageId());
//
        sysOrderOne.setUserId(SecurityUtils.getUserId());
        sysOrderOne.setDeptId(SecurityUtils.getDeptId());
//        sysOrderOne.setUserId(1l);
//        sysOrderOne.setDeptId(100l);

        sysOrderOne.setCreateTime(new Date());
        sysOrderOne.setCreateBy(SecurityUtils.getUsername());

        SysAgent sysAgent = agentMapper.selectSysAgentById(sysStore.getAgentId());
        sysOrderOne.setAgentName(sysAgent.getName());

        //将订单插入
        sysOrderOneMapper.insertSysOrderOne(sysOrderOne);
        //封装未支付信息给前端：
        OrderOneVO orderOneVO = new OrderOneVO();
        BeanUtils.copyProperties(sysOrderOne,orderOneVO);

        //根据套餐id查询套餐的信息

        if (sysPackage==null) {
            throw new ServiceException("套餐信息有误");
        }
        if (sysPackage.getLineStatus().equals("0")) {
            //说明是线上套餐
            orderOneVO.setPackageStatus("线上套餐");
        }
        else if(sysPackage.getLineStatus().equals("1")) {
            orderOneVO.setPackageStatus("线下套餐");
        }
        orderOneVO.setPackageName(sysPackage.getName());
        //通过套餐映射表查对应的接口对象
        List<Long> packageIds = new ArrayList<>();
        packageIds.add(packageId);
        List<SysSurveyPackage> surveyPackages = packageMapper.selectSysPackageSuvery(packageIds);
        List<Long> surveyIds = surveyPackages.stream().map(SysSurveyPackage::getSurveyId).collect(Collectors.toList());
        List<SysSurvey> sysSurveys = surveyMapper.selectAllSysSurveyList();
        Map<Long, String> sysSurveysMap = sysSurveys.stream().collect(Collectors.toMap(SysSurvey::getId, c -> c.getName()));
        List<String> surveysNames = new ArrayList<>();
        for (Long surveyId : surveyIds) {
            surveysNames.add(sysSurveysMap.get(surveyId));
        }
        orderOneVO.setSurveyNames(surveysNames);
        orderOneVO.setPeopleNum(1);
        orderOneVO.setOneAmount(orderDTO.getAmount());
        orderOneVO.setAllAmount(orderDTO.getAmount().multiply(new BigDecimal(orderOneVO.getPeopleNum())) );

        orderOneVO.setBalance(sysStore.getBalance());
        orderOneVO.setOneOrMore("0");  //代表是单人背调

        //消息通知
        //单人背调下单：
        SysOrder sysOrder = new SysOrder();
        BeanUtils.copyProperties(sysOrderOne,sysOrder);
        notifyUtils.MakeOrder(sysOrder);






        return orderOneVO;
    }

    @Override
    @Transactional
    public void payOrders(OrderOneVO orderOneVO) {
        //先判断订单是否存在

        Long id = orderOneVO.getId();
        SysOrderOne sysOrderOne=null;
        SysOrderParent sysOrderParent=null;
        if (orderOneVO.getOneOrMore().equals("0")) {
            //单人背调
             sysOrderOne = sysOrderOneMapper.selectSysOrderOneById(id);
            if (sysOrderOne==null) {
                throw new ServiceException("背调订单不存在,请返回重试");
            }
            if (!sysOrderOne.getOrderStatus().equals(0l)) {
                throw new ServiceException("背调订单状态异常，不可支付");
            }

        }
        if (orderOneVO.getOneOrMore().equals("1")) {
            //批量背调
            sysOrderParent = orderParentMapper.selectSysOrderParentById(id);
            if (sysOrderParent==null) {
                throw new ServiceException("批量订单不存在,请返回重试");
            }
            if (!sysOrderParent.getPayStatus().equals(0l)) {
                throw new ServiceException("批量订单状态异常，不可支付");
            }
        }


        //查看当前订单是否处于待支付状态



        //判断当前商户的余额是否充足
        //todo 换成当前登录用户的deptId
//        Long deptId = orderOneVO.getDeptId();
        Long deptId = SecurityUtils.getDeptId();
        if (!deptId.equals(orderOneVO.getDeptId())) {
            throw new ServiceException("当前用户没有权限操作该订单");
        }
        List<SysStore> sysStores = sysStoreMapper.selectSysStoreByDeptId(deptId);
        if (CollectionUtils.isEmpty(sysStores)) {
            throw new ServiceException("当前用户没有权限进行背调");
        }
        BigDecimal balance = sysStores.get(0).getBalance();

        if (balance.compareTo(orderOneVO.getAllAmount())<1) {
            throw new ServiceException("当前商户余额不足");
        }

        //判断当前商铺是否为代理商下的，如果是则进行余额判断，并扣费
        Long agentId = sysStores.get(0).getAgentId();
        SysAgent sysAgent = agentMapper.selectSysAgentById(agentId);
        if (!agentId.equals(0l)) {
            //进行代理商扣费

            if (sysAgent==null) {
                throw new ServiceException("代理商不存在");
            }
            Long setmealId = orderOneVO.getSetmealId();
            //查询对应的接口id
            List<Long> packageIds = new ArrayList<>();
            packageIds.add(setmealId);
            List<SysSurveyPackage> surveyPackages = packageMapper.selectSysPackageSuvery(packageIds);
            Set<Long> collect = surveyPackages.stream().map(SysSurveyPackage::getSurveyId).collect(Collectors.toSet());
            List<Long> surveyIds = new ArrayList<>(collect);

            //查询对应的代理商接口价格
            List<SysInterfacePrice> interfacePrices = interfacePriceMapper.selectByAgentId(agentId);
            if (CollectionUtils.isEmpty(interfacePrices) ||interfacePrices.size()>1) {
                throw new ServiceException("您的代理商未配置接口价格，请联系后重试");
            }
            SysInterfacePrice sysInterfacePrice = interfacePrices.get(0);
            BigDecimal amount = new BigDecimal("0.00");
            for (Long surveyId : surveyIds) {
                if (surveyId.equals(1l)) {
                    //信贷风险接口
                    BigDecimal creditPrice = sysInterfacePrice.getCreditPrice();
                    amount=  amount.add(creditPrice);
                    continue;
                }
                if (surveyId.equals(2l)) {
                    //学历
                    amount=   amount.add(sysInterfacePrice.getEducationPrice());
                    continue;

                }
                if (surveyId.equals(3l)) {
                    //学位
                    amount=   amount.add(sysInterfacePrice.getDegreePrice());
                    continue;
                }
                if (surveyId.equals(4l)) {
                    //工商
                    amount=     amount.add(sysInterfacePrice.getCommercialPrice());
                    continue;
                }
                if (surveyId.equals(5l)) {
                    //身份信息
                    amount=    amount.add(sysInterfacePrice.getIdentityPrice());
                    continue;
                }
                if (surveyId.equals(6l)) {
                    //公安不良
                    amount=   amount.add(sysInterfacePrice.getNegativePrice());
                    continue;

                }


            }

            BigDecimal amountDown = amount.setScale(2, RoundingMode.DOWN);
            BigDecimal allAmount = amountDown.multiply(new BigDecimal(orderOneVO.getPeopleNum()));



            BigDecimal agentBalance = sysAgent.getBalance();

            if (agentBalance.compareTo(allAmount)==-1) {
                //说明余额不足
                throw new ServiceException("代理商余额不足以本次背调，请联系代理商充值");
            }


            //进行代理商扣费
           int i = agentMapper.updateBalance(agentId,allAmount);
            if (i<=0) {
                throw new ServiceException("支付失败,请检查代理商余额");
            }


            //扣费成功向消费明细表插入数据

            SysExpendDetails sysExpendDetailsAgent = new SysExpendDetails();
            String stringRandomAgent = AmountReduceImpl.getStringRandom(10);
            sysExpendDetailsAgent.setExchangeMark(stringRandomAgent);
            sysExpendDetailsAgent.setStoreId(sysStores.get(0).getId());
            sysExpendDetailsAgent.setStoreName(sysStores.get(0).getName());
            sysExpendDetailsAgent.setAgentId(sysStores.get(0).getAgentId());
            sysExpendDetailsAgent.setType("4");
            sysExpendDetailsAgent.setExchangeAmount(allAmount);
            sysExpendDetailsAgent.setBalance(agentBalance.subtract(allAmount));
            String number="";
            Long setmealIdAgentId =null;
            if (orderOneVO.getOneOrMore().equals("0")) {
                number= sysOrderOne.getNumber();
                setmealIdAgentId = sysOrderOne.getSetmealId();
            }
            else if (orderOneVO.getOneOrMore().equals("1")){
                number = sysOrderParent.getNumber();
                setmealIdAgentId = sysOrderParent.getSetmealId();

            }


            SysPackage sysPackage = packageMapper.selectSysPackageById(setmealIdAgentId);

            sysExpendDetailsAgent.setDataId(orderOneVO.getId());
            sysExpendDetailsAgent.setUserId(SecurityUtils.getUserId());
            sysExpendDetailsAgent.setDeptId(SecurityUtils.getDeptId());
            sysExpendDetailsAgent.setCreateTime(new Date());
            sysExpendDetailsAgent.setCreateBy(SecurityUtils.getUsername());
            sysExpendDetailsAgent.setAgentName(sysAgent.getName());
            sysExpendDetailsAgent.setContent("订单编号:"+number+"/套餐:"+sysPackage.getName()+"/1人/操作人:"+SecurityUtils.getUsername());

            expendDetailsMapper.insertSysExpendDetails(sysExpendDetailsAgent);

        }

        //进行商铺余额的扣减
      int i=sysStoreMapper.PayOrder(sysStores.get(0).getId(),orderOneVO.getAllAmount());

        if (i<=0) {
            throw new ServiceException("支付失败,请检查店铺余额");
        }
        //支付成功后查询对应商铺
        SysStore sysStore = sysStoreMapper.selectSysStoreById(sysStores.get(0).getId());

        //根据订单id查询到对应订单对象
        SysExpendDetails sysExpendDetails = new SysExpendDetails();
        //支付成功,修改订单的状态和进度
        SysUser sysUser = userMapper.selectUserById(orderOneVO.getUserId());
        if (orderOneVO.getOneOrMore().equals("0")) {
            //单人背调
             SysOrderOne sysOrderOne1 = new SysOrderOne();
             sysOrderOne1.setId(orderOneVO.getId());
             sysOrderOne1.setOrderStatus(1L);
             sysOrderOne1.setPayStatus(1l);
             sysOrderOneMapper.updateSysOrderOne(sysOrderOne1);

             //消费明细表插入数据

            String stringRandom = AmountReduceImpl.getStringRandom(10);
            sysExpendDetails.setExchangeMark(stringRandom);
            sysExpendDetails.setStoreId(sysStores.get(0).getId());
            sysExpendDetails.setStoreName(sysStores.get(0).getName());
            sysExpendDetails.setAgentId(sysStores.get(0).getAgentId());
            sysExpendDetails.setType("2");
            sysExpendDetails.setExchangeAmount(orderOneVO.getAllAmount());
            sysExpendDetails.setBalance(sysStores.get(0).getBalance().subtract(orderOneVO.getAllAmount()));
            String number = sysOrderOne.getNumber();
            Long setmealId = sysOrderOne.getSetmealId();
            SysPackage sysPackage = packageMapper.selectSysPackageById(setmealId);

            sysExpendDetails.setDataId(orderOneVO.getId());
            sysExpendDetails.setUserId(SecurityUtils.getUserId());
            sysExpendDetails.setDeptId(SecurityUtils.getDeptId());
//            sysExpendDetails.setUserId(1l);
//            sysExpendDetails.setDeptId(100l);
            sysExpendDetails.setAgentName(sysAgent.getName());
            sysExpendDetails.setContent("订单编号:"+number+"/套餐:"+sysPackage.getName()+"/1人/操作人:"+sysUser.getUserName());
        }
        else if (orderOneVO.getOneOrMore().equals("1")) {
            //说明是批量订单：
            //修改批量订单表的状态
            SysOrderParent sysOrderParent1 = new SysOrderParent();
            sysOrderParent1.setId(orderOneVO.getId());
            sysOrderParent1.setPayStatus(1l);  //修改为已支付
            sysOrderParent1.setStatus(1l);    //设置为进行中

            //TODO
            //遍历修改内部单个表的状态
           List<SysOrderOne> orderOnes= sysOrderOneMapper.selectSysOrderOneByParentId(orderOneVO.getId());

            for (SysOrderOne orderOne : orderOnes) {

                orderOne.setPayStatus(1l);
                orderOne.setOrderStatus(1L);
                orderOne.setOrderOutcome(1L);
                sysOrderOneMapper.updateSysOrderOne(orderOne);
            }


            //添加消费明细表内容
            //消费明细表插入数据

            String stringRandom = AmountReduceImpl.getStringRandom(10);
            sysExpendDetails.setExchangeMark(stringRandom);
            sysExpendDetails.setStoreId(sysStores.get(0).getId());
            sysExpendDetails.setStoreName(sysStores.get(0).getName());
            sysExpendDetails.setAgentId(sysStores.get(0).getAgentId());
            sysExpendDetails.setType("3");
            sysExpendDetails.setExchangeAmount(orderOneVO.getAllAmount());
            sysExpendDetails.setBalance(sysStores.get(0).getBalance().subtract(orderOneVO.getAllAmount()));
            //查询对应的批量订单
            SysOrderParent sysOrderParent2 = orderParentMapper.selectSysOrderParentById(orderOneVO.getId());


            String number = sysOrderParent2.getNumber();
            Long setmealId = sysOrderParent2.getSetmealId();
            SysPackage sysPackage = packageMapper.selectSysPackageById(setmealId);
            //SysUser sysUser = userMapper.selectUserById(orderOneVO.getUserId());
            sysExpendDetails.setDataId(orderOneVO.getId());
            sysExpendDetails.setUserId(SecurityUtils.getUserId());
            sysExpendDetails.setDeptId(SecurityUtils.getDeptId());
//           sysExpendDetails.setUserId(1l);
//            sysExpendDetails.setDeptId(100l);
            sysExpendDetails.setContent("订单编号:"+number+"/套餐:"+sysPackage.getName()+"/"+sysOrderParent2.getCdNumber()+"人/操作人:"+sysUser.getUserName());
        }

        //执行插入操作消费明细操作
        sysExpendDetails.setCreateTime(new Date());
        sysExpendDetails.setCreateBy(sysUser.getUserName());
        expendDetailsMapper.insertSysExpendDetails(sysExpendDetails);

        //商户余额检测是否已经到预警值

        notifyUtils.CheckStorePrice(sysStore.getDeptId());
        //消息通知



        if (orderOneVO.getOneOrMore().equals("0")) {

            SysOrder sysOrder = new SysOrder();
            BeanUtils.copyProperties(sysOrderOne,sysOrder);
            notifyUtils.MakeOrder(sysOrder);
        }

        else if(orderOneVO.getOneOrMore().equals("1")) {
            notifyUtils.MakeOrders(sysOrderParent);

        }

        //todo 发送短信给对应的用户手机：


        //判断是批量还是单个
        if (orderOneVO.getOneOrMore().equals("0")) {

            Long orderId = orderOneVO.getId();
            //获取到订单的数据
            SysOrderOne sysOrderOne1 = sysOrderOneMapper.selectSysOrderOneById(orderId);
            if (sysOrderOne1!=null) {
                String url = OrderUtils.MakeHttpLink(sysOrderOne1);

                //todo 路径短链接转换：


                Map<String,String> infoMap = new HashMap<>();
                infoMap.put("phone",sysOrderOne1.getPhone());
                infoMap.put("store",sysOrderOne1.getStoreName());
                infoMap.put("web",url);
                infoMap.put("orderId",orderId.toString());

                String infoMapString = JSONObject.toJSONString(infoMap);

                //向mq发送对应的消息
                rabbitTemplate.convertAndSend("sendSMS",infoMapString);

//                try {
//                    SmsVariableSend smsVariableSend = new SmsVariableSend();
//                    boolean b = smsVariableSend.sendLink(infoMap);
//                } catch (UnsupportedEncodingException e) {
//                    throw new ServiceException("短信发送错误");
//                }


            }

        }

        else if(orderOneVO.getOneOrMore().equals("1")) {

            //通过查询所有订单

            List<SysOrderOne> orderOnes = sysOrderOneMapper.selectSysOrderOneByParentId(orderOneVO.getId());
            if (!CollectionUtils.isEmpty(orderOnes)) {
                for (SysOrderOne orderOne : orderOnes) {
                    String url = OrderUtils.MakeHttpLink(orderOne);

                    //todo 路径短链接转换：

                    Map<String,String> infoMap = new HashMap<>();
                    infoMap.put("phone",orderOne.getPhone());
                    infoMap.put("store",orderOne.getStoreName());
                    infoMap.put("web",url);
                    infoMap.put("orderId",orderOne.getId().toString());
                    String infoMapString = JSONObject.toJSONString(infoMap);

                    //向mq发送对应的消息
                    rabbitTemplate.convertAndSend("sendSMS",infoMapString);



                }
            }


        }










    }

    @Override
    public OrderOneVO submitMoreOrder(OrderDTO orderDTO) {

        //处理批量订单
         Long packageId = orderDTO.getPackageId();
         SysPackage sysPackage = packageMapper.selectSysPackageById(packageId);
        SysOrderParent sysOrderParent = new SysOrderParent();
        String Num = OrderUtils.MakeMoreOrderByDate(new Date());
        sysOrderParent.setNumber(Num);
        sysOrderParent.setCdNumber(Long.valueOf(orderDTO.getUserInfos().size()));
        sysOrderParent.setPayStatus(0l);
        sysOrderParent.setAmount(orderDTO.getAmount());
        //获取当前用户的商户信息：
        Long deptId = SecurityUtils.getDeptId();
//        Long deptId = 100l;

        List<SysStore> sysStores = sysStoreMapper.selectSysStoreByDeptId(deptId);
        if (CollectionUtils.isEmpty(sysStores)) {
            throw new ServiceException("当前用户商户信息有误");
        }
        SysStore sysStore = sysStores.get(0);

        sysOrderParent.setStoreId(sysStore.getId());
        sysOrderParent.setAgentId(sysStore.getAgentId());
        sysOrderParent.setSetmealId(orderDTO.getPackageId());
        sysOrderParent.setStoreName(sysStore.getName());
        sysOrderParent.setOrderStatus(0l);
        sysOrderParent.setCreateTime(new Date());
        sysOrderParent.setUserId(SecurityUtils.getUserId());
        sysOrderParent.setDeptId(SecurityUtils.getDeptId());
//        sysOrderParent.setUserId(1l);
//        sysOrderParent.setDeptId(100l);
        sysOrderParent.setAgentName(sysStore.getAgentName());
        orderParentMapper.insertSysOrderParent(sysOrderParent);

        //解析批量信息，生成对应的单个订单
        //生成一个摸板对象
        SysOrderOne sysOrderOne = new SysOrderOne();
        sysOrderOne.setAmount(orderDTO.getAmount().divide(new BigDecimal(orderDTO.getPeopleNum())));
        sysOrderOne.setAuthorizationType(orderDTO.getAuthorizedType());
        sysOrderOne.setPayStatus(0l);
        sysOrderOne.setOrderStatus(0l);
        sysOrderOne.setOrderOutcome(1l);
        sysOrderOne.setStoreId(sysStore.getId());
        sysOrderOne.setStoreName(sysStore.getName());
        sysOrderOne.setAgentId(sysStore.getAgentId());
        sysOrderOne.setSetmealId(packageId);
        sysOrderOne.setParentId(sysOrderParent.getId());
        sysOrderOne.setCreateBy(SecurityUtils.getUsername());
//        sysOrderOne.setCreateBy("吕宇宏001");
        sysOrderOne.setCreateTime(new Date());
        sysOrderOne.setUserId(SecurityUtils.getUserId());
        sysOrderOne.setDeptId(SecurityUtils.getDeptId());
//        sysOrderOne.setUserId(1l);
//        sysOrderOne.setDeptId(100l);

        //遍历批量内部信息
        List<UserInfoDTO> userInfos = orderDTO.getUserInfos();
        List<SysOrderOne> orderOnes = new ArrayList<>();
        for (UserInfoDTO userInfo : userInfos) {
            //创建一个新对象存储摸版内容
            SysOrderOne orderOne= new SysOrderOne();
            BeanUtils.copyProperties(sysOrderOne,orderOne);

            //生成编号
            String orderNum = OrderUtils.MakeOrderByDate(sysPackage.getLineStatus(),new Date());

            //添加单独信息
            orderOne.setNumber(orderNum);
            orderOne.setCdName(userInfo.getUserName());
            orderOne.setIdNumber(userInfo.getCard());
            orderOne.setPhone(userInfo.getPhone());
            if (userInfo.getGraduateCerNo()!=null) {
                orderOne.setCertificate(userInfo.getGraduateCerNo());
            }

            if (userInfo.getDegreeCerNo()!=null) {
                orderOne.setDegreeCerNo(userInfo.getDegreeCerNo());
            }


            //添加到集合中
            orderOnes.add(orderOne);
        }

        //执行批量插入订单
        sysOrderOneMapper.insertBatch(orderOnes);


        //生成信息返回前端
        //封装未支付信息给前端：

        OrderOneVO orderOneVO = new OrderOneVO();
        BeanUtils.copyProperties(sysOrderParent,orderOneVO);

        //根据套餐id查询套餐的信息

        if (sysPackage==null) {
            throw new ServiceException("套餐信息有误");
        }
        if (sysPackage.getLineStatus().equals("0")) {
            //说明是线上套餐
            orderOneVO.setPackageStatus("线上套餐");
        }
        else if(sysPackage.getLineStatus().equals("1")) {
            orderOneVO.setPackageStatus("线下套餐");
        }
        orderOneVO.setPackageName(sysPackage.getName());
        //通过套餐映射表查对应的接口对象
        List<Long> packageIds = new ArrayList<>();
        packageIds.add(packageId);
        List<SysSurveyPackage> surveyPackages = packageMapper.selectSysPackageSuvery(packageIds);
        List<Long> surveyIds = surveyPackages.stream().map(SysSurveyPackage::getSurveyId).collect(Collectors.toList());
        List<SysSurvey> sysSurveys = surveyMapper.selectAllSysSurveyList();
        Map<Long, String> sysSurveysMap = sysSurveys.stream().collect(Collectors.toMap(SysSurvey::getId, c -> c.getName()));
        List<String> surveysNames = new ArrayList<>();
        for (Long surveyId : surveyIds) {
            surveysNames.add(sysSurveysMap.get(surveyId));
        }
        orderOneVO.setSurveyNames(surveysNames);
        orderOneVO.setPeopleNum(orderDTO.getPeopleNum());
        orderOneVO.setOneAmount(orderDTO.getAmount().divide(new BigDecimal(orderDTO.getPeopleNum())));
        orderOneVO.setAllAmount(orderDTO.getAmount() );


        orderOneVO.setBalance(sysStore.getBalance());

        orderOneVO.setOneOrMore("1");  //多人背调

        //消息通知
        //单人背调下单：


        notifyUtils.MakeOrders(sysOrderParent);

        return orderOneVO;

    }

    @Override
    public void empowerUser(Long orderId, String msg, HttpServletRequest request, HttpServletResponse response) {

        //查询订单是否存在：
        SysOrderOne sysOrderOne = sysOrderOneMapper.selectSysOrderOneById(orderId);
        if (sysOrderOne==null) {
            throw new ServiceException("订单不存在");
        }

        //查询redis对应的校验码是否正确
        String key = "order_empower_"+orderId;
        String o = (String) redisTemplate.opsForValue().get(key);

        if (!msg.equals(o)) {
            throw new ServiceException("验证码错误，请重新发送");
        }

        //判断redis中是否已经进行接口查询了，
        String oneMinuteKey = "order_survey_isStart_"+orderId;
        Object o1 = redisTemplate.opsForValue().get(oneMinuteKey);
        if (!Objects.isNull(o1)) {
            //说明调用接口还未超过一分钟就要继续调用了，阻止
            throw new ServiceException("请问重复授权背调");
        }


        //查看订单状态是否为待授权

        Long orderStatus = sysOrderOne.getOrderStatus();
        if (!orderStatus.equals(1l)) {
            throw new ServiceException("当前订单状态异常，不可授权");
        }




        //表示这次操作是真实的

        //修改对应的订单表的状态
        SysOrderOne sysOrderOne1 = new SysOrderOne();
        sysOrderOne1.setId(sysOrderOne.getId());
        sysOrderOne1.setOrderStatus(2l);
        sysOrderOneMapper.updateSysOrderOne(sysOrderOne1);


        //发送通知;
        SysOrder sysOrder = new SysOrder();
        BeanUtils.copyProperties(sysOrderOne,sysOrder);
        notifyUtils.UserAuthorized(sysOrder);


        redisTemplate.opsForValue().set(oneMinuteKey,1,1, TimeUnit.MINUTES);

//        //异步执行背调操作
//        SurveyUtils surveyUtils =
//                new SurveyUtils(surveyMapper, packageMapper, creditMapper,
//                        degreesMapper, degreeDetailsMapper, educationDetailsMapper,
//                        commercialMapper, legalInfosMapper, shareholderInfosMapper,
//                        managerInfosMapper, punishedsMapper, punishBreaksMapper,
//                        adminPenaltyMapper, identityMapper, identityCasesMapper,
//                        identitySxbzxrMapper, xgbzxrMapper, dsrxxMapper, negativeMapper,
//                        negativeDetailsMapper, reportDetailsMapper, sysOrderOneMapper, redisTemplate, wordExportController);
        String sysOrderString = JSONObject.toJSONString(sysOrder);
        rabbitTemplate.convertAndSend("backtone",sysOrderString);

//        surveyUtils.SurveyImp(sysOrderOne, request, response);

       //调用操作之后添加一个





    }

    @Override
    public List<SysOrderOne> getSysOrderOneList(SysOrderOne sysOrderOne, Date beginCreateTime, Date endCreateTime) {
        return sysOrderOneMapper.getSysOrderOneList(sysOrderOne,beginCreateTime,endCreateTime);
    }

    @Override
    public AjaxResult getUserInfo(Long orderId) {

        //判断当前订单是否存在
        SysOrderOne orderOne = sysOrderOneMapper.selectSysOrderOneById(orderId);

        if (orderOne==null) {
            throw new ServiceException("订单不存在");
        }

        Long orderStatus = orderOne.getOrderStatus();
        Integer isAuthorized = 1;
        if (orderStatus.equals(0l) || orderStatus.equals(1l)) {
            isAuthorized = 0;
        }

        SysOrderUserInfo sysOrderUserInfo = new SysOrderUserInfo(orderOne.getCdName(), OrderUtils.maskPhoneNumber(orderOne.getPhone()),OrderUtils.maskIDCard(orderOne.getIdNumber()) , isAuthorized);



        //封装数据




        return AjaxResult.success(sysOrderUserInfo);
    }

    @Override
    public AjaxResult sendAgain(Long orderId) {

        //查询当前
        SysOrderOne orderOne = sysOrderOneMapper.selectSysOrderOneById(orderId);
        if (orderOne==null) {
            //订单不存在
            throw new ServiceException("订单不存在");
        }

        String web = OrderUtils.MakeHttpLink(orderOne);
        Map<String,String> linkMap =new HashMap<>();
        linkMap.put("phone",orderOne.getPhone());
        linkMap.put("store",orderOne.getStoreName());
        linkMap.put("web",web);
        linkMap.put("orderId",orderId.toString());


        String infoMapString = JSONObject.toJSONString(linkMap);

        //向mq发送对应的消息
        rabbitTemplate.convertAndSend("sendSMS",infoMapString);

        return AjaxResult.success("短信发送成功");
    }

    @Override
    public List<SysOrderSurveyVO> listOrderReports(Long orderId,Long types) {
        //判断当前订单是否存在

        SysOrderOne orderOne = sysOrderOneMapper.selectSysOrderOneById(orderId);
        if (orderOne==null) {
            throw new ServiceException("订单不存在");
        }
        //查询对应的report_details表
        List<SysOrderSurveyVO> orderSurveys = new ArrayList<>();
        if (types.equals(0l)) {

            List<Long> orderIds = new ArrayList<>();
            orderIds.add(orderId);
            List<SysReportDetails> reportDetails = reportDetailsMapper.selectSysReportDetailsByIds(orderIds);

            Map<String,SysOrderSurveyVO> surveyVOMap = new HashMap<>();

            if (!CollectionUtils.isEmpty(reportDetails)) {
                for (SysReportDetails sysReportDetails : reportDetails) {
                    String type = sysReportDetails.getType();
                    Long surveyResult = sysReportDetails.getSurveyResult();
                    if (type.equals("0")) {

                        //首先判断map中是否有 1 的 数据 ，如果有 是否风险为 1/2
                        if(!surveyVOMap.containsKey("1")) {
                            //直接进行操作
                            Long Result = sysReportDetails.getSurveyResult();
                            SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "个人身份信息", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                            surveyVOMap.put("1",identity);
                            continue;

                        }
                        else {
                            //判断里面的数据是否为无风险
                            SysOrderSurveyVO sysOrderSurveyVO = surveyVOMap.get("1");
                            Long result = sysOrderSurveyVO.getSurveyResult();
                            if (result.equals(2l) || result.equals(1l)) {
                                //说明报告可以被覆盖
                                if (!sysReportDetails.getSurveyResult().equals(2l)&&!sysReportDetails.getSurveyResult().equals(1l)) {
                                    //覆盖
                                    sysOrderSurveyVO.setSurveyResult(sysReportDetails.getSurveyResult());

                                }
                            }
                            continue;
                        }
                    }
                    if (type.equals("1")) {
                        //首先判断map中是否有 1 的 数据 ，如果有 是否风险为 1/2
                        if(!surveyVOMap.containsKey("2")) {
                            //直接进行操作
                            Long Result = sysReportDetails.getSurveyResult();
                            SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "社会安全信息", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                            surveyVOMap.put("2",identity);
                            continue;

                        }
                        else {
                            //判断里面的数据是否为无风险
                            SysOrderSurveyVO sysOrderSurveyVO = surveyVOMap.get("2");
                            Long result = sysOrderSurveyVO.getSurveyResult();
                            if (result.equals(2l) || result.equals(1l)) {
                                //说明报告可以被覆盖
                                if (!sysReportDetails.getSurveyResult().equals(2l)&&!sysReportDetails.getSurveyResult().equals(1l)) {
                                    //覆盖
                                    sysOrderSurveyVO.setSurveyResult(sysReportDetails.getSurveyResult());

                                }
                            }
                            continue;
                        }

                    }
                    if (type.equals("2")) {
                        //首先判断map中是否有 1 的 数据 ，如果有 是否风险为 1/2
                        if(!surveyVOMap.containsKey("2")) {
                            //直接进行操作
                            Long Result = sysReportDetails.getSurveyResult();
                            SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "社会安全信息", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                            surveyVOMap.put("2",identity);
                            continue;

                        }
                        else {
                            //判断里面的数据是否为无风险
                            SysOrderSurveyVO sysOrderSurveyVO = surveyVOMap.get("2");
                            Long result = sysOrderSurveyVO.getSurveyResult();
                            if (result.equals(2l) || result.equals(1l)) {
                                //说明报告可以被覆盖
                                if (!sysReportDetails.getSurveyResult().equals(2l)&&!sysReportDetails.getSurveyResult().equals(1l)) {
                                    //覆盖
                                    sysOrderSurveyVO.setSurveyResult(sysReportDetails.getSurveyResult());

                                }
                            }
                            continue;
                        }


                    }
                    if (type.equals("3") || type.equals("4") || type.equals("5") || type.equals("6") || type.equals("7") || type.equals("8")) {

                        //首先判断map中是否有 1 的 数据 ，如果有 是否风险为 1/2
                        if(!surveyVOMap.containsKey("3")) {
                            //直接进行操作
                            Long Result = sysReportDetails.getSurveyResult();
                            SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "个人信用信息", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                            surveyVOMap.put("3",identity);
                            continue;

                        }
                        else {
                            //判断里面的数据是否为无风险
                            SysOrderSurveyVO sysOrderSurveyVO = surveyVOMap.get("3");
                            Long result = sysOrderSurveyVO.getSurveyResult();
                            if (result.equals(2l) || result.equals(1l)) {
                                //说明报告可以被覆盖
                                if (!sysReportDetails.getSurveyResult().equals(2l)&&!sysReportDetails.getSurveyResult().equals(1l)) {
                                    //覆盖
                                    sysOrderSurveyVO.setSurveyResult(sysReportDetails.getSurveyResult());

                                }
                            }
                            continue;
                        }


                    }

                    if (type.equals("9")) {
                        //首先判断map中是否有 1 的 数据 ，如果有 是否风险为 1/2
                        if(!surveyVOMap.containsKey("4")) {
                            //直接进行操作
                            Long Result = sysReportDetails.getSurveyResult();
                            SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "商业利益冲突", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                            surveyVOMap.put("4",identity);
                            continue;

                        }
                        else {
                            //判断里面的数据是否为无风险
                            SysOrderSurveyVO sysOrderSurveyVO = surveyVOMap.get("4");
                            Long result = sysOrderSurveyVO.getSurveyResult();
                            if (result.equals(2l) || result.equals(1l)) {
                                //说明报告可以被覆盖
                                if (!sysReportDetails.getSurveyResult().equals(2l)&&!sysReportDetails.getSurveyResult().equals(1l)) {
                                    //覆盖
                                    sysOrderSurveyVO.setSurveyResult(sysReportDetails.getSurveyResult());

                                }
                            }
                            continue;
                        }


                    }
                    if (type.equals("10")) {
                        //首先判断map中是否有 1 的 数据 ，如果有 是否风险为 1/2
                        if(!surveyVOMap.containsKey("5")) {
                            //直接进行操作
                            Long Result = sysReportDetails.getSurveyResult();
                            SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "法院诉讼", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                            surveyVOMap.put("5",identity);
                            continue;

                        }
                        else {
                            //判断里面的数据是否为无风险
                            SysOrderSurveyVO sysOrderSurveyVO = surveyVOMap.get("5");
                            Long result = sysOrderSurveyVO.getSurveyResult();
                            if (result.equals(2l) || result.equals(1l)) {
                                //说明报告可以被覆盖
                                if (!sysReportDetails.getSurveyResult().equals(2l)&&!sysReportDetails.getSurveyResult().equals(1l)) {
                                    //覆盖
                                    sysOrderSurveyVO.setSurveyResult(sysReportDetails.getSurveyResult());

                                }
                            }
                            continue;
                        }


                    }
                    if (type.equals("11") || type.equals("12")) {
                        //首先判断map中是否有 1 的 数据 ，如果有 是否风险为 1/2
                        if(!surveyVOMap.containsKey("6")) {
                            //直接进行操作
                            Long Result = sysReportDetails.getSurveyResult();
                            SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "教育经历", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                            surveyVOMap.put("6",identity);
                            continue;

                        }
                        else {
                            //判断里面的数据是否为无风险
                            SysOrderSurveyVO sysOrderSurveyVO = surveyVOMap.get("6");
                            Long result = sysOrderSurveyVO.getSurveyResult();
                            if (result.equals(2l) || result.equals(1l)) {
                                //说明报告可以被覆盖
                                if (!sysReportDetails.getSurveyResult().equals(2l)&&!sysReportDetails.getSurveyResult().equals(1l)) {
                                    //覆盖
                                    sysOrderSurveyVO.setSurveyResult(sysReportDetails.getSurveyResult());

                                }
                            }
                            continue;
                        }


                    }
                    if (type.equals("13")) {

                      //type大于12说明是接口调用失败导致

                            //直接进行操作
                            Long Result = sysReportDetails.getSurveyResult();
                            SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "信贷风险", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                        surveyVOMap.put("13",identity);
                            continue;




                }
                    if (type.equals("14")) {

                        //type大于12说明是接口调用失败导致

                        //直接进行操作
                        Long Result = sysReportDetails.getSurveyResult();
                        SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "学历核实", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                        surveyVOMap.put("14",identity);
                        continue;




                    }
                    if (type.equals("15")) {

                        //type大于12说明是接口调用失败导致

                        //直接进行操作
                        Long Result = sysReportDetails.getSurveyResult();
                        SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "学位核实", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                        surveyVOMap.put("15",identity);
                        continue;




                    }
                    if (type.equals("16")) {

                        //type大于12说明是接口调用失败导致

                        //直接进行操作
                        Long Result = sysReportDetails.getSurveyResult();
                        SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "个人工商", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                        surveyVOMap.put("16",identity);
                        continue;




                    }
                    if (type.equals("17")) {

                        //type大于12说明是接口调用失败导致

                        //直接进行操作
                        Long Result = sysReportDetails.getSurveyResult();
                        SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "身份信息", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                        surveyVOMap.put("17",identity);
                        continue;




                    }
                    if (type.equals("18")) {

                        //type大于12说明是接口调用失败导致

                        //直接进行操作
                        Long Result = sysReportDetails.getSurveyResult();
                        SysOrderSurveyVO identity = new SysOrderSurveyVO(sysReportDetails.getCreateTime(), "公安不良", sysReportDetails.getSurveyStatus(), sysReportDetails.getSurveyResult(), sysReportDetails.getReportUrl());
                        surveyVOMap.put("18",identity);
                        continue;


                    }
                    }
            }


            surveyVOMap.keySet().stream().forEach(key ->{
                orderSurveys.add(surveyVOMap.get(key));
            });

//        //查询对应的report表
//        List<SysReport> sysReports = reportMapper.selectListByOrderId(orderOne.getId());
//
//         if (!CollectionUtils.isEmpty(sysReports)) {
//
//             for (SysReport sysReport : sysReports) {
//
//                 SysOrderSurveyVO sysOrderSurveyVO = new SysOrderSurveyVO(convertToDate(sysReport.getCreateTime()), "——————", Long.valueOf(sysReport.getStatus()), Long.valueOf(sysReport.getResult()), sysReport.getUrl());
//                 orderSurveys.add(sysOrderSurveyVO);
//
//
//
//             }
//
//         }

            Collections.sort(orderSurveys, new Comparator<SysOrderSurveyVO>() {
                @Override
                public int compare(SysOrderSurveyVO o1, SysOrderSurveyVO o2) {
                    return o2.getUploadTime().compareTo(o1.getUploadTime());
                }
            });

            return orderSurveys;
        }

        else if(types.equals(1l)) {
            //线下手动上传

          List<SysReport> reports=  reportMapper.selectDwonListByOrderId(orderId);


            for (SysReport report : reports) {
                SysOrderSurveyVO linkDown = new SysOrderSurveyVO(convertToDate(report.getCreateTime()), "线下报告", Long.valueOf(report.getStatus()), Long.valueOf(report.getResult()), report.getUrl());
                orderSurveys.add(linkDown);
            }
        }



        //封装对应的数据


        //根据时间排序返回
        return orderSurveys;



    }

    @Override
    public List<SysOrderOneVO> getSysOrderOneVOList(SysOrderOneVO sysOrderOneVO) {
        List<SysOrderOneVO> list = sysOrderOneMapper.getSysOrderOneVOList(sysOrderOneVO);
        for (SysOrderOneVO orderOneVO: list){
            if (orderOneVO.getLineStatus()!=null){
                if (orderOneVO.getLineStatus().equals("0")){
                    orderOneVO.setLineStatus("线上");
                }else {
                    orderOneVO.setLineStatus("线下");
                }
            }
            if (orderOneVO.getOrderOutcome()!=null){
                if(orderOneVO.getOrderOutcome()==1){
                    orderOneVO.setOrderOutcomeName("待出具");
                }else if(orderOneVO.getOrderOutcome()==2){
                    orderOneVO.setOrderOutcomeName("无风险");
                }else if(orderOneVO.getOrderOutcome()==3){
                    orderOneVO.setOrderOutcomeName("低风险");
                }else if(orderOneVO.getOrderOutcome()==4){
                    orderOneVO.setOrderOutcomeName("中风险");
                }else {
                    orderOneVO.setOrderOutcomeName("高风险");
                }
            }
            if (orderOneVO.getOrderStatus()!=null){
                if (orderOneVO.getOrderStatus()==0){
                    orderOneVO.setOrderStatusName("发起被调");
                }else if(orderOneVO.getOrderStatus()==1){
                    orderOneVO.setOrderStatusName("待授权");
                }else if(orderOneVO.getOrderStatus()==2){
                    orderOneVO.setOrderStatusName("背调中");
                }else if(orderOneVO.getOrderStatus()==3){
                    orderOneVO.setOrderStatusName("已出报告");
                }else if(orderOneVO.getOrderStatus()==4){
                    orderOneVO.setOrderStatusName("异常");
                }else {
                    orderOneVO.setOrderStatusName("挂起");
                }

            }

        }

        return list;
    }

    @Override
    public List<SysOrderOneVO> getSysOrderOneVOListOther(SysOrderOneVO sysOrderOneVO, Long deptId) {
        List<SysOrderOneVO> list = sysOrderOneMapper.getSysOrderOneVOListOther(sysOrderOneVO,deptId);
        for (SysOrderOneVO orderOneVO: list){
            if (orderOneVO.getLineStatus()!=null){
                if (orderOneVO.getLineStatus().equals("0")){
                    orderOneVO.setLineStatus("线上");
                }else {
                    orderOneVO.setLineStatus("线下");
                }
            }
            if (orderOneVO.getOrderOutcome()!=null){
                if(orderOneVO.getOrderOutcome()==1){
                    orderOneVO.setOrderOutcomeName("待出具");
                }else if(orderOneVO.getOrderOutcome()==2){
                    orderOneVO.setOrderOutcomeName("无风险");
                }else if(orderOneVO.getOrderOutcome()==3){
                    orderOneVO.setOrderOutcomeName("低风险");
                }else if(orderOneVO.getOrderOutcome()==4){
                    orderOneVO.setOrderOutcomeName("中风险");
                }else {
                    orderOneVO.setOrderOutcomeName("高风险");
                }
            }
            if (orderOneVO.getOrderStatus()!=null){
                if (orderOneVO.getOrderStatus()==0){
                    orderOneVO.setOrderStatusName("发起被调");
                }else if(orderOneVO.getOrderStatus()==1){
                    orderOneVO.setOrderStatusName("待授权");
                }else if(orderOneVO.getOrderStatus()==2){
                    orderOneVO.setOrderStatusName("背调中");
                }else if(orderOneVO.getOrderStatus()==3){
                    orderOneVO.setOrderStatusName("已出报告");
                }else if(orderOneVO.getOrderStatus()==4){
                    orderOneVO.setOrderStatusName("异常");
                }else {
                    orderOneVO.setOrderStatusName("挂起");
                }

            }

        }

        return list;
    }

    @Override
    public String getUserNameById(Long userId) {
        return sysOrderOneMapper.getUserNameById(userId);
    }

    public static Date convertToDate(LocalDateTime localDateTime) {
        // 将LocalDateTime与默认时区结合转换为ZonedDateTime
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());

        // 将ZonedDateTime转换为Instant
        Instant instant = zonedDateTime.toInstant();

        // 将Instant转换为Date
        return Date.from(instant);
    }
}
